package com.tc168.cp306.b06.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.litesuits.common.assist.Network;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tc168.cp306.b06.R;
import com.tc168.cp306.b06.Utils.SPUtils;
import com.tc168.cp306.b06.Utils.ToastUtil;
import com.tc168.cp306.b06.fragment.BangzhuFragment;
import com.tc168.cp306.b06.fragment.GuanyuFragment;
import com.tc168.cp306.b06.fragment.HistoryFragment;
import com.tc168.cp306.b06.fragment.JIluFragment;
import com.tc168.cp306.b06.fragment.MainFragment;
import com.tc168.cp306.b06.fragment.NoteFragment;
import com.tc168.cp306.b06.fragment.SousuoFragment;
import com.tc168.cp306.b06.fragment.YijianFragment;
import com.tc168.cp306.b06.iview.AppStatusInfo;
import com.tc168.cp306.b06.iview.NoticeDialog;
import com.tc168.cp306.b06.iview.UpdateManager2;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener, NoticeDialog.OnNoticeDialogClickListener, EasyPermissions.PermissionCallbacks {

    private static final String TAG = "MainActivity";

    private Context mContext;
    private DrawerLayout mDlMain;
    private FrameLayout mFlContent;
    private LinearLayout mRlLeft, mRlRight;


    private ImageView mBtnOpenLeftDrawer;


    private MainFragment mainFragment;

    private String[] leftMenuNames = {"left_item1", "left_item2",
            "left_item3", "left_item4"};
    private NoteFragment noteFragment;
    private HistoryFragment historyFragment;
    private SousuoFragment sousuoFragment;
    private YijianFragment yijianFragment;
    private BangzhuFragment bangzhuFragment;
    private MatterActivity matterActivity;
    private GuanyuFragment guanyuFragment;

    private FrameLayout counnt;
    private FragmentManager fragmentManager;
    private FragmentTransaction ft;
    private ImageView btnopenleftdrawer;
    private FrameLayout flcontent;
    private LinearLayout cone;
    private LinearLayout ctwo;
    private LinearLayout cthree;
    private LinearLayout cfour;
    private LinearLayout cfive;
    private LinearLayout csix;
    private LinearLayout cseven;
    private LinearLayout ceight;
    private LinearLayout cabout;
    private LinearLayout cexit;
    private LinearLayout rlleft;

    private LinearLayout tuichu;
    private DrawerLayout dlmain;
    private int index = 0;

    private List<Fragment> fragments;
    private String[] tags;
    private JIluFragment jIluFragment;


    private NoticeDialog mNoticeDialog;
    private String downloadUrl = null;
    private String[] perms;
    private static final int RC_CAMERA_AND_LOCATION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null)
            initView();
    }

    private void initView() {

        setContentView(R.layout.activity_main);

        this.rlleft = (LinearLayout) findViewById(R.id.rl_left);
        this.cexit = (LinearLayout) findViewById(R.id.c_exit);
        this.cabout = (LinearLayout) findViewById(R.id.c_about);
        this.ceight = (LinearLayout) findViewById(R.id.c_eight);
        this.cseven = (LinearLayout) findViewById(R.id.c_seven);
        this.csix = (LinearLayout) findViewById(R.id.c_six);
        this.cfive = (LinearLayout) findViewById(R.id.c_five);
        this.cfour = (LinearLayout) findViewById(R.id.c_four);
        this.cthree = (LinearLayout) findViewById(R.id.c_three);
        this.ctwo = (LinearLayout) findViewById(R.id.c_two);
        this.cone = (LinearLayout) findViewById(R.id.c_one);
        this.flcontent = (FrameLayout) findViewById(R.id.fl_content);
        this.counnt = (FrameLayout) findViewById(R.id.counnt);
        this.btnopenleftdrawer = (ImageView) findViewById(R.id.btn_open_left_drawer);

        this.tuichu = (LinearLayout) findViewById(R.id.tuichu);
        cexit.setOnClickListener(this);
        cone.setOnClickListener(this);
        ctwo.setOnClickListener(this);
        cthree.setOnClickListener(this);
        cfour.setOnClickListener(this);
        cfive.setOnClickListener(this);
        csix.setOnClickListener(this);
        cseven.setOnClickListener(this);
        ceight.setOnClickListener(this);
        cabout.setOnClickListener(this);
        tuichu.setOnClickListener(this);

        mContext = this;
        counnt = (FrameLayout) findViewById(R.id.counnt);


        mDlMain = (DrawerLayout) findViewById(R.id.dl_main);

        mDlMain.setScrimColor(Color.TRANSPARENT);//去除左右抽屉划出后内容显示页背景的灰色
//        mDlMain.setDrawerShadow();//填充抽屉划出后与屏幕边缘之间的内容
        mFlContent = (FrameLayout) findViewById(R.id.fl_content);
        mRlLeft = (LinearLayout) findViewById(R.id.rl_left);

        mBtnOpenLeftDrawer = (ImageView) findViewById(R.id.btn_open_left_drawer);
        mBtnOpenLeftDrawer.setOnClickListener(this);


        mainFragment = new MainFragment();

        noteFragment = new NoteFragment();
        historyFragment = new HistoryFragment();
        sousuoFragment = new SousuoFragment();
        yijianFragment = new YijianFragment();
        bangzhuFragment = new BangzhuFragment();
        matterActivity = new MatterActivity();
        guanyuFragment = new GuanyuFragment();

        jIluFragment = new JIluFragment();

        tags = new String[]{"mainFragment", "noteFragment", "historyFragment", "sousuoFragment"
                , "yijianFragment", "bangzhuFragment", "jIluFragment", "guanyuFragment"
        };

        MProgressDialog.showProgress(this);


        new Handler().postDelayed(new Runnable() {

            @Override

            public void run() {
                MProgressDialog.dismissProgress();
            }
        }, 1000);
        fragmentManager = getSupportFragmentManager();

        fragments = new ArrayList<Fragment>();
        fragments.add(mainFragment);
        fragments.add(noteFragment);
        fragments.add(historyFragment);
        fragments.add(sousuoFragment);
        fragments.add(yijianFragment);
        fragments.add(bangzhuFragment);
        fragments.add(jIluFragment);
        fragments.add(guanyuFragment);
        ChangeFragment(0);


        getPermission();


//        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "persondb.db");
//        Database db = helper.getWritableDb();
//        DaoSession daoSession = new DaoMaster(db).newSession();
//        TopticbeanDao dao = daoSession.getTopticbeanDao();
//
//        List<Topticbean> list = dao.queryBuilder().where(TopticbeanDao.Properties.Toptictype.eq(1)).list();
//        Toast.makeText(this, list.get(0).getJieshi(), Toast.LENGTH_LONG).show();


//        perms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
//        if (EasyPermissions.hasPermissions(this, perms)) {
//            uodateExp();
//            // 已经申请过权限，做想做的事
//        } else {
//            // 没有申请过权限，现在去申请
//            EasyPermissions.requestPermissions(this, "app更新软件权限",
//                    RC_CAMERA_AND_LOCATION, perms);
//        }


    }

    //左侧菜单点击事件
    @Override
    public void onItemClick(AdapterView<?> pAdapterView, View pView, int pI, long pL) {
        android.support.v4.app.Fragment lFragment = new MenuFragment();
        Bundle lBundle = new Bundle();
        lBundle.putString("menu_str", "item_" + (pI + 1));
        lFragment.setArguments(lBundle);
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.fl_content, lFragment).commit();

        mDlMain.closeDrawers();

    }

    @Override
    public void onClick(View pView) {
        switch (pView.getId()) {
            case R.id.btn_open_left_drawer:
                mDlMain.openDrawer(Gravity.LEFT);

                break;
            case R.id.c_exit:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ToastUtil.showLong(this, "已经是最新版本了，3.11.40");
                } else {
                    gologin();
                }
            case R.id.c_about:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ChangeFragment(7);
                } else {
                    gologin();
                }
                break;
            case R.id.c_one:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ChangeFragment(0);
                } else {
                    gologin();
                }
                break;
            case R.id.c_two:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ChangeFragment(1);
                } else {
                    gologin();
                }
                break;
            case R.id.c_three:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ChangeFragment(2);
                } else {
                    gologin();
                }
                break;
            case R.id.c_four:
                mDlMain.closeDrawers();

                if (getLoginStatus()) {
                    ChangeFragment(3);
                } else {
                    gologin();
                }
                break;
            case R.id.c_five:
                mDlMain.closeDrawers();
                if (getLoginStatus()) {
                    ChangeFragment(4);

                } else {
                    gologin();
                }
                break;
            case R.id.c_six:
                mDlMain.closeDrawers();
                if (getLoginStatus()) {
                    ChangeFragment(5);

                } else {
                    gologin();
                }
                break;
            case R.id.c_seven:
                mDlMain.closeDrawers();
                if (getLoginStatus()) {
                    ChangeFragment(6);

                } else {
                    gologin();
                }
                break;

            case R.id.c_eight:
                mDlMain.closeDrawers();
                if (getLoginStatus()) {

                } else {
                    gologin();
                }

                break;

            case R.id.tuichu:
                if (getLoginStatus()) {
                    SPUtils.put(MainActivity.this, "isdeng", false);
                    SPUtils.put(MainActivity.this, "name", "");


                } else {
                    gologin();
                }
                break;


        }
    }


    private void gologin() {
        Intent a = new Intent(this, LoginActivity.class);
        startActivity(a);
    }

    //判断登录状态
    protected boolean getLoginStatus() {
        return (boolean) SPUtils.get(this, "isdeng", false);//设置等级
    }

    private void ChangeFragment(int i) {
        FragmentTransaction beginTransaction = fragmentManager.beginTransaction();
        if (index != i) {
            if (!fragments.get(i).isAdded()) {
                beginTransaction.hide(fragments.get(index)).add(R.id.counnt, fragments.get(i), tags[i]);
            } else {
                beginTransaction.hide(fragments.get(index)).show(fragments.get(i));
            }
            index = i;

        } else {
            if (!fragments.get(i).isAdded()) {

                beginTransaction.add(R.id.counnt, fragments.get(i), tags[i]);
            } else {
                beginTransaction.show(fragments.get(i));
            }
        }

        if (!isFinishing()) {
            beginTransaction.commitAllowingStateLoss();
            getSupportFragmentManager().executePendingTransactions();
        }
    }


    //获取必要权限
    private void getPermission(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果应用之前请求过此权限但用户拒绝了请求，返回 true。
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                updateExp();
            }
        } else {
            updateExp();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    updateExp();
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }
            }
        }
    }

    /**
     * 检测app
     * http://aagcp.top/appStatus/getAppStatusInfo?appId=com.tc168.c04&Platform=baidu
     */
    public void updateExp() {
        StringBuffer sb = new StringBuffer();
        sb.append("http://aagcp.top/appStatus/getAppStatusInfo");
        sb.append("?");
        sb.append("appId=");
        sb.append(getApplictionId());
        sb.append("&Platform=");//新加参数
        sb.append("qq");

        OkHttpUtils.get().url(sb.toString()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                Gson gson = new Gson();
                AppStatusInfo appStatusInfo = gson.fromJson(response,AppStatusInfo.class);
                if (appStatusInfo.getErrorcode().equals(String.valueOf(0))){
                    AppStatusInfo.Result result = appStatusInfo.getResult();
                    int status = result.getStatus();
                    String packageString = result.getAppKey();

                    PackageManager packageManager = getPackageManager();
                    Intent intent = packageManager.getLaunchIntentForPackage(packageString);

                    if (status == 1) {
                        if (intent == null){
                            downloadUrl = result.getUrl();
                            if (null != downloadUrl && downloadUrl.length() > 0){
                                updateApp();
                            }
                        }
                        else {
                            //包名相同替换
                            if (packageString.equals(getApplictionId())){
                                downloadUrl = result.getUrl();
                                if (null != downloadUrl && downloadUrl.length() > 0){
                                    updateApp();
                                }
                            } else {
                                startActivity(intent);
                                finish();
                            }

                        }
                    }

                }
            }
        });
    }

    /**
     * 更新app
     */
    public void updateApp() {
        UpdateManager2 updateManager = new UpdateManager2(this);
        updateManager.setUrl(downloadUrl);
        updateManager.update();
    }


    /**
     * 获取app版本号
     *
     * @return 版本号
     */
    public String getVersion() {

        PackageManager packageManager = getApplication().getPackageManager();
        String versionName = null;
        try {
            versionName = packageManager.getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (Exception e) {
        }
        return versionName;
    }


    /**
     * 获取app ApplictionId
     *
     * @return ApplictionId
     */
    public String getApplictionId() {
        return this.getPackageName();
    }
    @Override
    public void onConfirmClick() {
        mNoticeDialog.dismiss();
        updateApp();
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    //更新失败调用
    @Override
    public void onPermissionsDenied(int requestCode, List<String> permsw) {
        EasyPermissions.requestPermissions(this, "app更新软件权限",
                RC_CAMERA_AND_LOCATION, perms);
    }


}
